package com.eduction.controller;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.eduction.bean.SessionUser;
import com.eduction.service.SurveyOpinionService;
import com.eduction.vo.SurveyPointCountVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eduction.common.Hash;
import com.eduction.common.ReturnCode;
import com.eduction.common.dbutil.page.Page;
import com.eduction.modules.system.entity.CityEntity;
import com.eduction.modules.system.entity.School;
import com.eduction.modules.system.entity.SchoolType;
import com.eduction.resource.BaseController;
import com.eduction.service.SchoolService;

@Controller
@RequestMapping("/school")
public class SchoolController extends BaseController{

private static final Log logger = LogFactory.getLog(SchoolContactController.class);
	
	@Autowired
	private SchoolService schoolService;

	@Autowired
	private SurveyOpinionService surveyOpinionService;
	
	/**
	 * 分页查询学校
	 */
	@RequestMapping(value = "/querySchoolByPage" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> querySchoolByPage(HttpServletRequest request,@RequestBody Map<String ,String> map) {
		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return toResponse(null,ReturnCode.FAIL,"暂无权限！");
		}

		if(map.get("pageNumber") == null || map.get("pageSize") == null || StringUtils.isBlank(map.get("pageNumber")) || StringUtils.isBlank(map.get("pageSize"))){
			return	toResponse(null, ReturnCode.FAIL, "参数不能为空!");
		}
		try {
			Page<School> page = schoolService.querySchoolByPage(map);
			return toResponse(page, ReturnCode.SUCCESS, "分页查询成功!");
		} catch (SQLException e) {
			logger.error(e);
			return toResponse(null, ReturnCode.SUCCESS, "分页查询失败!");
		}
	}

	/**
	 * 分页查询学校
	 */
	@RequestMapping(value = "/querySchoolByCount" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> querySchoolByCount(HttpServletRequest request,@RequestBody Map<String ,String> map) {

		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return toResponse(null,ReturnCode.FAIL,"暂无权限！");
		}
		String schoolType = map.get("schoolType");//0-优质学校，1-现代化学校
		String expectType = map.get("expectType");//0-材料评审，1-现场考察
		if(schoolType== null ||expectType== null ){
			return	toResponse(null, ReturnCode.FAIL, "参数不能为空!");
		}

		try {
			List<School> schoolList=new ArrayList<>();
			List<School> list = schoolService.queryBySchoolType(schoolType);
			List<SurveyPointCountVo> voList=surveyOpinionService.queryByCount(expectType);
			for(SurveyPointCountVo vo:voList){
				for(School s:list){
					if(s.getP_id().equals(vo.getS_school_id())){
						schoolList.add(s);
						break;
					}
				}
			}
			return toResponse(schoolList, ReturnCode.SUCCESS, "分页查询成功!");
		} catch (SQLException e) {
			logger.error(e);
			return toResponse(null, ReturnCode.SUCCESS, "分页查询失败!");
		}
	}


	/**
	 * 修改学校信息
	 */
	@RequestMapping(value = "/updateSchool" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> updateSchool(HttpServletRequest request,@RequestBody Map<String ,String> map) {
		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return toResponse(null,ReturnCode.FAIL,"暂无权限！");
		}

		String s_id = map.get("s_id");
		String name = map.get("name");
		String c_id = map.get("c_id");
		String t_id = map.get("t_id");
		if(s_id == null){
			return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "参数为空");
		}
		try {
			School sc = schoolService.querySchoolByAccount(s_id);
			if(sc == null)
				return toResponse(null, ReturnCode.FAIL, "该学校不存在");
			if(name == null || StringUtils.isBlank(name))
				return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "名字不能为空");
			if(c_id == null || StringUtils.isBlank(c_id))
				return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "城市名不能为空");
			if(t_id == null || StringUtils.isBlank(t_id))
				return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "类型不能为空");
			
			sc.setS_name(StringUtils.trim(name));
			sc.setP_city_id(c_id);
			sc.setP_type_id(t_id);
			schoolService.saveSchool(sc);
			return toResponse(null,ReturnCode.SUCCESS,"修改成功");
		} catch (SQLException e) {
			logger.error(e);
			return toResponse(null,ReturnCode.FAIL,"修改失败");
		}
	}
	
	/**
	 * 修改学校密码
	 */
	@RequestMapping(value = "/updateSchoolPass" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> updateStringPass(HttpServletRequest request,@RequestBody Map<String,String> map){
		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return toResponse(null,ReturnCode.FAIL,"暂无权限！");
		}

		String s_id = map.get("s_id");
		String oldPass = map.get("oldPass");
		String newPass = map.get("newPass");
		if(s_id == null || oldPass == null || newPass == null || StringUtils.isBlank(s_id) || StringUtils.isBlank(oldPass) || StringUtils.isBlank(newPass)){
			return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"参数为空");
		}
		try {
			School sc = schoolService.querySchoolByAccount(s_id);
			if(sc == null){
				return toResponse(null,ReturnCode.FAIL,"该学校不存在");
			}
			if(!sc.getP_password().equals(Hash.sha2InHex(oldPass))){
				return toResponse(null, ReturnCode.FAIL, "原密码错误");
			}
			if(oldPass.equals(newPass)){
				return toResponse(null,ReturnCode.FAIL,"新旧密码不能相同");
			}
			sc.setP_password(Hash.sha2InHex(newPass));
			schoolService.saveSchool(sc);
			return toResponse(null, ReturnCode.SUCCESS, "密码修改成功");
		} catch (SQLException e) {
			logger.error(e);
			return toResponse(null, ReturnCode.FAIL, "密码修改失败");
		}
	}
	
	/**
	 * 查询所有城市和学校类型
	 */
	@RequestMapping(value = "/queryCityAndType")
	@ResponseBody
	public ResponseEntity<String> queryCityAndType(Model model){
		try {
			List<CityEntity> citys = schoolService.queryCities();
			List<SchoolType> types = schoolService.querySchoolType();
			model.addAttribute("citys", citys);
			model.addAttribute("types", types);
			return toResponse(null, ReturnCode.SUCCESS, "查询城市和类型成功");
		} catch (SQLException e) {
			e.printStackTrace();
			return toResponse(null, ReturnCode.FAIL, "查询城市和类型失败");
		}
	}
	
	/**
	 * 添加学校
	 */
	@RequestMapping(value = "/saveSchool",produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> saveSchool(HttpServletRequest request,@RequestBody Map<String,String> map){

		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return toResponse(null,ReturnCode.FAIL,"暂无权限！");
		}
		String p_id=map.get("p_id");
		String name = map.get("name");
		String c_id = map.get("c_id");
		String t_id = map.get("t_id");
		String year = map.get("year");
		if(name == null || StringUtils.isBlank(name))
			return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "名字不能为空");
		if(c_id == null || StringUtils.isBlank(c_id))
			return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "城市名不能为空");
		if(t_id == null || StringUtils.isBlank(t_id))
			return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "类型不能为空");
		if(year == null || StringUtils.isBlank(year))
			return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "参评年度不能为空");

		try {
            School s=schoolService.querySchoolByAccount(p_id);
            if(s!=null){
                return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "学校编号已存在");
            }
			School sc = new School();
			sc.setP_id(p_id);
			sc.setS_name(StringUtils.trim(name));
			sc.setP_city_id(c_id);
			sc.setP_type_id(t_id);
			sc.setP_password(Hash.sha2InHex("111111"));
			sc.setS_state("1");
			sc.setYear(year);
			schoolService.saveSchool(sc);
			return toResponse(null, ReturnCode.SUCCESS, "新增学校成功");
		} catch (Exception e) {
			e.printStackTrace();
			return toResponse(null, ReturnCode.FAIL, "新增学校失败");
		}
	}
	
	/**
	 * 删除学校
	 */
	@RequestMapping(value = "/deleteSchool",produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> deleteSchool(HttpServletRequest request,@RequestBody Map<String,String> map){
		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return toResponse(null,ReturnCode.FAIL,"暂无权限！");
		}

		String p_id = map.get("p_id");
		if(p_id == null || StringUtils.isBlank(p_id)){
			return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "参数为空");
		}
		try {
			School s = schoolService.querySchoolByAccount(p_id);
			if(s == null){
				return toResponse(null, ReturnCode.FAIL, "该学校不存在");
			}
			schoolService.deleteSchool(p_id);
			return toResponse(null, ReturnCode.SUCCESS, "删除学校成功");
		} catch (SQLException e) {
			e.printStackTrace();
			return toResponse(null, ReturnCode.FAIL, "删除学校失败");
		}
	}	
}
